package net.projecteuler.prob;

import net.projecteuler.util.DigitUtil;

public class Problem74 implements Runnable {

	private int[] digitFactorial = null;
	private int[] sdf = null;
	
	@Override
	public void run() {
		initialize();
		
		int cnt = 0;
		for(int i = 0; i < 1000000; i++){
			int non = getNonRepeating2(i);
//			System.out.println(i + " : " + non);
			if(non == 60){
				cnt++;
//				System.out.println(i);
			}
		}
		
		System.out.println("cnt : " + cnt);
	}
	
	private void initialize(){
		digitFactorial = new int[10];
		digitFactorial[0] = 1;
		for(int i = 1; i < 10; i++)
			digitFactorial[i] = digitFactorial[i - 1] * i;
		
		sdf = new int[1000000];
		for(int i = 0; i < 1000000; i++){
			int[] digits = DigitUtil.digits(i);
			int sum = 0;
			
			for(int j = 0; j < digits.length; j++)
				sum += digitFactorial[digits[j]];
			
			sdf[i] = sum;
		}
	}
	
	private int getSDF(int val){
		int[] digits = DigitUtil.digits(val);
		int sum = 0;
		
		for(int j = 0; j < digits.length; j++)
			sum += digitFactorial[digits[j]];
		
		return sum;
	}
	
	private int getNonRepeating(int val){
		int[] chain = new int[100];
		
		int cnt = 0;
		chain[cnt] = val;
		while(true){
			cnt++;
			chain[cnt] = sdf[chain[cnt - 1]];
			for(int j = 0; j < cnt; j++){
				if(chain[cnt] == chain[j]){
					return cnt;
				}
			}
		}
	}
	
	private int getNonRepeating2(int val){
		int[] chain = new int[100];
		
		int cnt = 0;
		chain[cnt] = val;
		while(true){
			cnt++;
			chain[cnt] = getSDF(chain[cnt - 1]);
			for(int j = 0; j < cnt; j++){
				if(chain[cnt] == chain[j]){
					return cnt;
				}
			}
		}
	}
	
}
